package com.jlboot.core.util;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jlboot.core.exception.JlServerException;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wangsanfei
 * @version 1.0
 * Create by 2024/3/21 09:06
 */
public class VoUtil {

    public static <T> Page<T> copyToPage(Page<Record> page,Class<T> tClass){
        List newList=copyToList(page.getList(),tClass);
        return new Page<>(newList,page.getPageNumber(),page.getPageSize(),page.getTotalPage(),page.getTotalRow());
    }

    public static <T> List<T> copyToList(List<Record> list, Class<T> tClass){
        List<T> newList=new ArrayList<>();
        for (Record record : list) {
            newList.add(copy(record,tClass));
        }
        return newList;
    }

    public static <T> T copy(Record record,Class<T> tClass){
        if(record==null){
            return null;
        }
        T o;
        try {
            Constructor<?> constructor = tClass.getConstructor();
            o = (T)constructor.newInstance();
            Field[] fields = tClass.getDeclaredFields();	// 获取对象的所有属性
            for (Field item : fields) {
                String name = item.getName();	// 获取对象属性名
                String typeName = item.getGenericType().getTypeName();	// 获取对象属性的类型
                item.setAccessible(true);
                Object value=record.get(name);
                if(value!=null){
                    if(value instanceof LocalDateTime){
                        if(typeName.equals("java.util.Date")){
                            ZonedDateTime zonedDateTime = ((LocalDateTime)value).atZone(ZoneId.systemDefault());
                            Instant instant = zonedDateTime.toInstant();
                            item.set(o,Date.from(instant));
                        }else{
                            item.set(o,value);
                        }
                    }else{
                        item.set(o,value);
                    }
                }


            }
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new JlServerException("构造对象失败",e);
        }

        return o;

    }

}
